//
//  SYOAuthViewController.swift
//  SYWeibo
//
//  Created by Eric on 16/7/20.
//  Copyright © 2016年 Eric. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class SYOAuthViewController: UIViewController {
    override func loadView() {
        //请求的url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URL)"
        
        //初始化一个url
        let url = NSURL(string: urlString)
        guard let u = url else{
            return
        }
        
        //初始化一个request
        let request = NSURLRequest(URL: u)
        webView.loadRequest(request)
        webView.delegate = self
        view = webView
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        progressView.removeVie()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    //MARK: -添加监听事件
    @objc private func cancelClick(){
        //移除控制器
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //MARK: -js的注入
    @objc private func authFillClick(){
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(vbName)',document.getElementById('passwd').value='\(vbPasswd)'"
        
        //js的注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    //MARK: -设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
        navigationController?.view.insertSubview(progressView, belowSubview: (navigationController!.navigationBar))
        setupNav()
        
    }
    
    //MARK: -设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "authFillClick")
        navigationItem.title = "微博登录"
        
        
        
    }
    // MARK: - 懒加载控件
    // 加载webView
    private lazy var webView: UIWebView = UIWebView()
    // 加载 webView 的进度条
    private lazy var  progressView: SYOAuthProgressView = SYOAuthProgressView()
    
}

extension SYOAuthViewController: UIWebViewDelegate {
    
    //开始加载V
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.startAnim()
        
    }
    //加载完成v
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.endAnim()
        
        
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        
    }
    /*
    监听webView 将要加载的request
    - 其有返回值
    - 如果返回为true 代表继续加载
    - 如果返回为false 带包要停止加载
    - 默认如果不实现该方法 默认为true
    
    */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //请求url的字符串
        let urlString = request.URL?.absoluteString
        
        //判断urlString 是否为nil 而且他的前缀为回调页
        if let u = urlString where u.hasPrefix(APPREDIRECT_URL) {
            // url 的请求参数
            let query = request.URL?.query
            if let q = query {
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
                print("终于等到你还好没放弃:\(code)")
                SYUserAccountViewModel.sharedTools.loadUserAccount(code, isSuccess: { (isSucc) -> () in
                    print(isSucc)
                    if !isSucc{
                        return
                    }
                    //先关闭当前的界面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //发送一个通知 告知appdelegate 切换控制
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                        
                    })
                })
                
                return false
            }
            
        }
        return true
    }
    
}

//MARK :  - 请求数据
extension SYOAuthViewController{
    //请求accessToken
    func getUserAccount(code: String){
        //请求urlString
        SYNetworkTools.sharedTool.oauthLoadUserAccount(code, success: {(response)->() in
            // 当在guard 或者if let中 使用as  一般情况下 都是使用as?
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
            return
            }
            //字典转模型
            let userAccout = SYUserAccount(dict: res)
            self.getUserInfo(userAccout)
            
            }){(error)->() in
                print("请求失败\(error)")
        
        }
        
}

    // 获取用户信息数据
    func getUserInfo(userAccount: SYUserAccount){
        
        SYNetworkTools.sharedTool.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
                return
            }
            // 因为当前的screenname 和avatar_large 本来就是可选值 所以在as的时候 只用as? 转字符串
            // 给其userAccount身上两个为nil的属性赋值
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            print(userAccount)
            }) { (error) -> () in
                print("请求失败:\(error)")
        }
    }
}















